﻿using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace SZHelperCore
{
    public static class MD5Helper
    {
        public static string FileMD5(this string path)
        {
            if (string.IsNullOrWhiteSpace(path))
                throw new ArgumentException("文件路径不能为空。", nameof(path));

            using var fileStream = File.OpenRead(path); // 自动处理 FileMode/Open/Share
            using var md5 = MD5.Create(); // ✅ 使用 Create() 替代 new MD5CryptoServiceProvider()
            byte[] hash = md5.ComputeHash(fileStream);
            return Convert.ToHexString(hash); // .NET 5+，自动大写，无需 Replace("-", "")
        }

        /// <summary>
        /// 计算字符串的 MD5 哈希值（大写十六进制字符串）
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <param name="encoding">编码，默认 UTF-8（推荐）</param>
        public static string StrMD5(this string str, Encoding encoding = null)
        {
            encoding ??= Encoding.UTF8; // ✅ 推荐 UTF-8 而非 Default

            if (string.IsNullOrEmpty(str))
                return Convert.ToHexString(MD5.HashData(Array.Empty<byte>())); // 空字符串的 MD5

            byte[] bytes = encoding.GetBytes(str);
            byte[] hash = MD5.HashData(bytes); // ✅ .NET 6+ 提供静态 HashData，无需 using
            return Convert.ToHexString(hash);
        }
        public static string GetPasswordMD5(string txtPwd)
        {
            string strRandom;

            //获取3位随机字母
            Random r = new Random();
            strRandom = ((char)(r.Next(65, 65 + 26))).ToString() + ((char)(r.Next(65, 65 + 26))).ToString() + ((char)(r.Next(65, 65 + 26))).ToString();

            return (strRandom + StrMD5(strRandom + txtPwd)).Substring(0,32);//设定加密方式，也可以在此进行多次Md5加强密码安全度
        }
        public static bool PasswordIsRight(string sqlPwd, string txtPwd)
        {
            string str = sqlPwd.Substring(0, 3);
            string tmp = str + StrMD5(str + txtPwd);
            var result = sqlPwd.ToLower() == tmp.Substring(0, 32).ToLower() ? true : false;
            return result;
        }
    }
}
